package com.dek.ssm.ch11.game;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyBeanUtil implements InvocationHandler{
	
	private Object object;
	
	private Interceptor interceptor = null;
	
	public static Object getBean(Object obj, Interceptor interceptor) {
		ProxyBeanUtil _this = new ProxyBeanUtil();
		_this.object = obj;
		_this.interceptor = interceptor;
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), _this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object returnObj = null;
		boolean exception = false;
		interceptor.before(object);
		try {
			returnObj = method.invoke(object, args);
		} catch (Exception e) {
			e.printStackTrace();
			exception = true;
		} finally {
			interceptor.after(object);
		}
		if (exception) {
			interceptor.afterThrowing(object);
		} else {
			interceptor.afterReturning(object);
		}
		return returnObj;
	}

}
